<?php

namespace App\Http\Controllers\Notice;

use App\Models\Notice\SmsRecord;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Validator;
use App\Helpers\Code;
use App\Models\Notice\SystemNotice;
use App\Models\Notice\NoticeRecord;
use App\Models\Notice\SmsError;

class NoticeController extends Controller
{

    public function __construct()
    {
        $this->_validations();
        $this->model = new SystemNotice();
    }

    /**
     * 发送系统通知 表单提交 post请求 操作表system_notices notice_records
     * @param title content created_by  type
     * @param receiver 为json格式uid字串
     */
    public function addSystemNotice(Request $request)
    {
        try {
            $data = $request->only($this->model->getFillable());
            $validator = Validator::make($data, $this->rules, $this->messages);
            if ($validator->fails()) {
                return $this->error($validator, Code::SYSTEM_VALIDATOR_ERROR);
            }

            if (!is_string($data['receiver'])) {
                return $this->error('common.data_format_error');
            }

            $receiver = json_decode($data['receiver']);
            if (!is_array($receiver)) {
                return $this->error('common.data_format_error');
            } else {
                $data['receiver'] = $receiver;
            }

            $data['created_by'] = $request->user()->id;
            $systemNotice = $this->model->addSystemNotice($data);
            $this->checked($systemNotice, [
                'null' => 'notice.add_notice_failure',
                Code::INSIDE_ERROR_1 => 'notice.add_record_failure',
                Code::INSIDE_EXIST_DEPENDENCE => 'notice.illegal_user_id'
            ]);

            return $this->result;
        } catch (\Exception $e) {
            return $this->throwError($e);
        }
    }

    /**
     * 删除系统自定模板 post请求 操作表system_notices
     * @param id  system_notice表中id
     */
    public function deleteSystemNotice($id)
    {
        try {
            $systemNotice = $this->model->deleteSystemNotice($id);
            $this->checked($systemNotice, ['null' => 'common.delete_failure', Code::INSIDE_ERROR_1 => 'notice.delete_notice_failure']);
            return $this->result;
        } catch (\Exception $e) {
            return $this->throwError($e);
        }
    }

    /**
     * 获取系统通知列表 管理员权限 get请求 查询system_notices
     */
    public function getSystemNoticeList(Request $request)
    {
        try {
            $search = $this->handleSearch($request, $this->model);
            $limit = (int) $request->input('limit');
            $sorter = $this->handleSort($request, $this->model->sorters);
            return preprocess($this->model->getSystemNoticeList($limit, $sorter, $search));
        } catch (\Exception $e) {
            return $this->throwError($e);
        }
    }

    /**
     * 发送系统通知获取通知内容和发送对象
     * @param id
     */
    public function getSystemNotice($id)
    {
        try {
            $systemNotice = $this->model->getSystemNotice($id);
            $this->checked($systemNotice, ["null" => 'common.get_failure']);
            return $this->result;
        } catch (\Exception $e) {
            return $this->throwError($e);
        }
    }

    /**
     * 登录用户获取收到的通知消息 查询sms_records notice_records表  get请求
     * @param  type=system获取notice_records表对应数据 type=sms获取sms_records表对用数据
     */
    public function getMyNoticeList(Request $request)
    {
        try {
            $search = $this->handleSearch($request, $this->model);
            $limit = (int) $request->input('limit');

            $type = $request->input('type');
            $userId = $request->user()->id;

            switch ($type) {
                case 'system':
                    $noticeRecord = new NoticeRecord();
                    $sorter = $this->handleSort($request, $noticeRecord->sorters);
                    return preprocess($noticeRecord->getMyNoticeList($userId, $limit, $sorter, $search));
                case 'sms':
                    $smsRecord = new SmsRecord();
                    $sorter = $this->handleSort($request, $smsRecord->sorters);
                    return preprocess($smsRecord->getMyNoticeList($userId, $limit, $sorter, $search, [Code::SMS_TYPE_0]));
                case 'message':
                    $smsRecord = new SmsRecord();
                    $sorter = $this->handleSort($request, $smsRecord->sorters);
                    return preprocess($smsRecord->getMyNoticeList($userId, $limit, $sorter, $search, [Code::SMS_TYPE_1, Code::SMS_TYPE_2]));
                case 'other':
                    $smsRecord = new SmsRecord();
                    $sorter = $this->handleSort($request, $smsRecord->sorters);
                    return preprocess($smsRecord->getMyNoticeList($userId, $limit, $sorter, $search, [Code::SMS_TYPE_3, Code::SMS_TYPE_4]));
                default :
                    return $this->error('notice.type_error');
            }
        } catch (\Exception $e) {
            return $this->throwError($e);
        }
    }

    /**
     * 用户点击收到的通知消息  修改状态为已读 操作notice_records表  post请求
     * @param  id系统自定义模板操作notice_records.notice_id
     */
    public function readNotice($noticeId, Request $request)
    {
        try {
            $userId = $request->user()->id;
            $noticeRecord = new NoticeRecord();
            $model = $noticeRecord->readNotice($userId, $noticeId);
            $this->checked($model, ['null' => 'common.get_failure']);
            return $this->result;
        } catch (\Exception $e) {
            return $this->throwError($e);
        }
    }

    /**
     * 获取发送失败的短信
     */
    public function getNoticeErrorList(Request $request)
    {
        try {
            $limit = (int) $request->input('limit');

            $smsError = new SmsError();
            return preprocess($smsError->getNoticeErrorList($limit));
        } catch (\Exception $e) {
            return $this->throwError($e);
        }
    }

    public function getNoticeListAll()
    {
        try {
            $this->result['data'] = $this->model->getNoticeListAll();

            return $this->result;
        } catch (\Exception $e) {
            return $this->throwError($e);
        }
    }

    public function clearNotices(Request $request)
    {
        try {
            $rules = [
                'type' => 'bail|required|in:system,sms,message',
                'notice' => 'required',
            ];

            $messages = [
                'type.required' => trans('notice.clear_type_required'),
                'type.in' => trans('notice.clear_type_in'),
                'notice.required' => trans('notice.clear_notice_required')
            ];

            $data = $request->only(['type', 'notice']);

            $validator = Validator::make($data, $rules, $messages);

            if ($validator->fails()) {
                return $this->error($validator, Code::SYSTEM_VALIDATOR_ERROR);
            }

            if (!is_array($data['notice'])) {
                return $this->error('common.data_format_error');
            }

            $model = $this->model->clearNotices($data);

            $this->checked($model, ['null' => 'common.handle_error']);

            return $this->result;
        } catch (\Exception $e) {
            return $this->throwError($e);
        }
    }

    public function _validations()
    {
        $this->rules = [
            'title' => 'required|max:50',
            'content' => 'required',
            'type' => 'required|in: 0,1',
//            'type' => 'in: 0,1',
            'receiver' => 'required',
        ];

        $this->messages = [
            'title.required' => trans('notice.title_required'),
            'title.max' => trans('notice.title_max'),
            'content.required' => trans('notice.content_required'),
            'type.required' => trans('notice.type_required'),
            'type.in' => trans('notice.type_in'),
            'receiver.required' => trans('notice.receiver'),
        ];
    }

}
